#!/usr/bin/env python
#
# Copyright 2009 Australian Online Solutions Pty Ltd
#                http://www.aos.net.au
# 
# Author: Sam Johnston <samj@samj.net>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import wsgiref.handlers
from google.appengine.ext import webapp
from time import time

#kickoff = 1230764400             # start at unix time for new years eve 2009
kickoff = 1233446399              # start at the end of january 2009
start = 74000000                  # first trademark serial issued
                                  # as at 20090121 we're up to 79063488
fast_rate = 6000000.0/(365*86400) # per second, to be done by year end
                                  # (((79063488-74000000)/(86400*0.17))/30)
slow_down = 80000000              # then slow down...
slow_rate = 20000.0/(86400.0*30)  # to around 20,000/m once we catch up
                                  # 10^6 serials since 2003-01-06 ~ 14,000/mth
                                  # 10^5 serials since 2008-08-07 ~ 18,000/mth
verify_tag = "\n<meta name=\"verify-v1\" " +
  "content=\"pfLAD4oKBdnelECRrcpR8gMZe3Jf19p4L4xk4FeC/6o=\" >\n"

class MainHandler(webapp.RequestHandler):

  def get(self):
    self.response.out.write(
"""
<html><head><title>Indexifier</title>%s</head><body>
<h1>Trademark Index</h1>
See <a href=\"http://code.google.com/p/indexifier/\">
http://code.google.com/p/indexifier/</a> for more information.
<p>A <a href="http://en.wikipedia.org/wiki/Trademark">trademark</a> or trade
mark or mark is a distinctive sign or indicator used by an individual,
business organization or other legal entity to identify that the products
and/or services to consumers with which the trademark appears originate from
a unique source of origin, and to distinguish its products or services from
those of other entities. A trademark is a type of intellectual property, and
typically a name, word, phrase, logo, symbol, design, image, or a combination
of these elements. There is also a range of non-conventional trademarks
comprising marks which do not fall into these standard categories.
The owner of a registered trademark may commence legal proceedings for
trademark infringement to prevent unauthorized use of that trademark. However,
registration is not required. The owner of a common law trademark may also
file suit, but an unregistered mark may be protectable only within the
geographical area within which it has been used or in geographical areas into
which it may be reasonably expected to expand.
The term trademark is also used informally to refer to any distinguishing
attribute by which an individual is readily identified, such as the well
known characteristics of celebrities. When a trademark is used in relation
to services rather than products, it may sometimes be called a service mark,
particularly in the United States.</p>
""" % verify_tag
    self.response.out.write("<ul>")
    for i in range(0, 100):
      self.response.out.write("<li><a href=\"%02d\">xxxxxx%02d</a></li>" % \
        (i,i))
    self.response.out.write("</ul></body></html>")

class TreeHandler(webapp.RequestHandler):
	
  def get(self, arg1=None, arg2=None):
    # regex's return strings
    arg1 = int(arg1)

    elapsed = time() - kickoff
    ceiling = start + (elapsed * fast_rate)
    self.response.out.write("<h1>Trademarks %d to %d</h1>" % (start, ceiling))
    if (ceiling > slow_down):
      ceiling = start + (elapsed * slow_rate)
      self.response.out.write("Target %d reached; rate slowed down from " + \
        "%0.4f to %0.4f per second." % (slow_down, fast_rate, slow_rate))
    else:
      self.response.out.write("Target %d not reached; fast indexing at " + \
        "%0.4f serials per second (thereafter at %0.4f per second)." % \
        (slow_down, fast_rate, slow_rate))
    self.response.out.write("<ul>")

    if (arg2 != None):
      arg2 = int(arg2)
      for i in range(int((start/(10**4))), int((ceiling/(10**4))+1)):
        sn = (i * 10**4) + (arg1 * 10**2) + arg2
        self.response.out.write( \
          "<li><a href=\"http://tarr.uspto.gov/servlet/tarr?" + \
          "regser=serial&entry=%08d\">%08d</a></li>" % (sn,sn))
    else:
      for i in range(0, 100):
        self.response.out.write("<li><a href=\"%02d/%02d\">" + \
          "xxxx%02d%02d</a></li>" % (arg1,i,arg1,i))
    self.response.out.write("</ul></body></html>")

class SitemapHandler(webapp.RequestHandler):

  def get(self):
    self.response.headers['Content-Type'] = 'text/xml'
    self.response.out.write('''<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://%s/</loc>
    <changefreq>daily</changefreq>
  </url>
''' % self.request.headers['host'])
    for i in range(0,100):
      for j in range(0,100):
        self.response.out.write("""<url>
  <loc>http://%s/%02d/%02d/</loc>
  <changefreq>daily</changefreq>
</url>""" % (self.request.headers['host'],i,j))
    self.response.out.write('</urlset>')

def main():
  application = webapp.WSGIApplication([('/', MainHandler),
                                        (r'/(\d\d)', TreeHandler),
                                        (r'/(\d\d)/(\d\d).*', TreeHandler),
                                        ('/sitemap.xml', SitemapHandler)
                                       ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
